﻿function AzureOnlineBlobsContainersListView(context) {

    var self = this;

    var spinner = new SpinnerModel();

    var blobContainers = context.blobs.containers;

    var spaRuntime = context.spaRuntime;

    var blobDetailsRoute = spaRuntime.findRouteByName('blobContainerDetails');

    var filter = ko.observable('');
    
    var details = new AzureOnlineBlobContainerCreateDetailsView(context);

    var filteredContainers = ko.computed(function () {
        var cnts = blobContainers();
        var f = filter();
        if (utils.isNullOrWhiteSpace(f)) return cnts;
        var wildcard = new Wildcard(f);
        var res = [];
        for (var i = 0; i < cnts.length; i++) {
            var cnt = cnts[i];
            if (wildcard.match(cnt.name())) {
                res.push(cnt);
            }
        }
        return res;
    });
    
    function reload() {
        spinner.enter();
        var api = context.api();
        api.blob.listContainers({
            success: function (raw) {
                spinner.leave();
                var res = [];
                var $doc = $(raw);

                var $items = $doc.find('EnumerationResults Container');
                $items.each(function () {
                    res.push(new AzureOnlineBlobContainer($(this)));
                });

                blobContainers(res);
            },
            error: function () {
                spinner.leave();
                blobContainers([]);
                return 'notify';
            }
        });
    }

    context.api.subscribe(function () {
        var api = context.api();
        if (api) {
            reload();
        }
    });
    
    ko.computed(function () {
        filter(context.blobs.blobsSettings().getItem('quickSearch') || '');
    }).extend({ throttle: 10 });

    ko.computed(function () {
        context.blobs.blobsSettings().setItem('quickSearch', filter());
    }).extend({ throttle: 10 });

    self.getBlobContainerDetailsUrl = function (blob) {
        return blobDetailsRoute.formatHash({
            blobName: blob.name()
        });
    };

    self.context = context;
    self.spinner = spinner;
    self.filter = filter;
    self.reload = reload;
    self.blobContainers = blobContainers;
    self.filteredContainers = filteredContainers;
    self.details = details;
}